<template>
  <div class="app-container">
    <div class="search-container">
      <el-form :model="searchParam" :inline="true">
        <el-form-item label="采集时间">
          <el-date-picker
            v-model="searchParam.collectionTimeSearch"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD HH:mm:ss"
            @change="getcollectionTime"
          />
        </el-form-item>
        <el-form-item label="设备类型">
          <el-select
            v-model="searchParam.deviceTypeCode"
            placeholder="请选择设备类型"
            clearable
            @keyup.enter="searchChange"
            @change="deviceTypeChage"
          >
            <el-option
              v-for="item in equipTypeList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="设备">
          <el-select
            v-model="searchParam.deviceCode"
            placeholder="请选择设备"
            clearable
            @keyup.enter="searchChange"
          >
            <el-option
              v-for="item in equipList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="searchChange"
            ><i-ep-search />搜索</el-button
          >
          <el-button @click="hadelReset"><i-ep-refresh />重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never" class="table-container">
      <el-table
        ref="dataTableRef"
        v-loading="loading"
        :data="tableData"
        highlight-current-row
        border
        @selection-change="handleSelectionChange"
      >
        <el-table-column
          label="采集时间"
          prop="collectionTime"
          min-width="120"
          show-overflow-tooltip
          sortable
        />
        <el-table-column
          label="设备编号"
          prop="deviceCode"
          min-width="120"
          show-overflow-tooltip
          sortable
        />
        <el-table-column
          label="采集数据"
          min-width="300"
          prop="dataText"
          show-overflow-tooltip
          sortable
        />
        <el-table-column fixed="right" label="操作" width="150" align="center">
          <template #default="scope">
            <el-button
              type="primary"
              size="small"
              link
              @click="openDialogdetail(scope.row)"
            >
              <i-ep-edit />
              详情
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        :background="true"
        :current-page="pageable.pageNum"
        :page-size="pageable.pageSize"
        :page-sizes="[10, 25, 50, 100]"
        :total="pageable.total"
        layout="total, sizes, prev, pager, next, jumper"
        class="mt-[20px]"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>

    <iotdevicedata-edit
      :visible="addDialog.visible"
      :title="addDialog.title"
      :data="addDialog.data"
      @reset-table="(id:string) => (id?.length ? getTableList() : getTableList())"
      :is-readonly="addDialog.readvisible"
      @change-visible="changeVisible"
    />
  </div>
</template>

<script setup lang="ts">
import { useTable, useDownload, useDictionary } from "@/utils/useTable";
import request from "@/utils/request";
import { number } from "echarts";
import dayjs from "dayjs";

defineOptions({
  name: "IOTDATAQUERY",
  inheritAttrs: false,
});

// 请求参数
const requestApi = "/iotadmin/deviceData/queryHistoryByPage";

// 是否需要分页
const pagination = true;

const initParam = {};

// 获取当前时间，number为空是当前时间，number为向前推几分钟
function getNowTime(num?: number) {
  // 创建一个 Date 对象
  var today = new Date();
  if (num) {
    today.setMinutes(today.getMinutes() + num);
  }

  // 获取年、月、日、时、分、秒
  let year = today.getFullYear();
  let month = today.getMonth() + 1; // 月份是从 0 开始计数的，需要加1
  let day = today.getDate();
  let hours = today.getHours();
  let minutes = today.getMinutes();
  let seconds = today.getSeconds();

  // 格式化输出
  let formattedTime =
    year +
    "-" +
    (month < 10 ? "0" : "") +
    month +
    "-" +
    (day < 10 ? "0" : "") +
    day +
    " " +
    (hours < 10 ? "0" : "") +
    hours +
    ":" +
    (minutes < 10 ? "0" : "") +
    minutes +
    ":" +
    (seconds < 10 ? "0" : "") +
    seconds;

  return formattedTime;
}

const getTimeStart = () => {
  const now = new Date();
  let midnight = dayjs(
    new Date(now.getFullYear(), now.getMonth(), now.getDate())
  ).format("YYYY-MM-DD HH:mm:ss");
  return midnight;
};
// 初始化搜索参数数据
const searchParamInit = {
  collectionTimeSearch: [getTimeStart(), getNowTime()],
  startTime: getTimeStart(),
  endTime: getNowTime(),
  deviceTypeCode: "",
  deviceCode: "",
};
// getTimeStart()
const deleteParam = {
  api: "/iotadmin/iotdevicedata/delete",
  data: {},
};
let isSameDay = ref(false);
// 点击搜索进行时间判断
const searchChange = () => {
  // 判断是否选择设备编号
  if (!searchParam.value.deviceCode) {
    ElMessage.warning("请选择设备编号！");
    return;
  }
  // 判断是否选择时间以及 是否是同一天
  if (!searchParam.value.collectionTimeSearch) {
    ElMessage.warning("请选择时间！");
  } else if (
    !searchParam.value.collectionTimeSearch[0] &&
    !searchParam.value.collectionTimeSearch[1]
  ) {
    ElMessage.warning("请选择时间！");
  } else {
    const start = dayjs(searchParam.value.collectionTimeSearch[0]);
    const end = dayjs(searchParam.value.collectionTimeSearch[1]);
    isSameDay.value = start.isSame(end, "day");
    if (isSameDay.value) {
      search();
    } else {
      ElMessage.warning("请选择同一天时间！");
    }
  }
};

// 数据请求错误后处理
function requestError() {}

const dataCallBack = ref(undefined); // 无需二次数据处理&不传赞数也行

// 表格操作 Hooks
const {
  tableData,
  pageable,
  searchParam,
  getTableList,
  search,
  reset,
  handleSizeChange,
  handleCurrentChange,
  handleSelectionChange,
  loading,
}: any = useTable(
  requestApi,
  initParam,
  searchParamInit,
  pagination,
  dataCallBack.value,
  requestError,
  deleteParam
);

onMounted(() => {
  getTableList();
  getEquipTypeList();
});

const addDialog = reactive<DialogOption>({
  visible: false,
  readvisible: false,
  title: "",
  data: {},
});

// 查询详情
async function getInfo(row: any) {
  const { data } = await request({
    url: `/iotadmin/deviceData/get/${row.deviceCode}/${row.id}`,
    method: "get",
  });
  addDialog.data = data;
}

/** 打开设备采集数据表单弹窗 详情 */
function openDialogdetail(roleObj?: any) {
  addDialog.title = "设备采集数据详情";
  getInfo(roleObj);
  addDialog.readvisible = true;
  addDialog.visible = true;
}

function changeVisible(value: boolean) {
  addDialog.visible = value;
  if (!value) {
    addDialog.data = {};
  }
}

function getcollectionTime(data: any) {
  if (data) {
    searchParam.value.startTime = data[0];
    searchParam.value.endTime = data[1];
  } else {
    searchParam.value.startTime = "";
    searchParam.value.endTime = "";
  }
}

// 获取设备类型下拉框
const equipTypeList: any = ref([]);
const getEquipTypeList = async () => {
  const res = await request({
    url: "/iotadmin/scaequiptype/getlist",
    method: "post",
    data: {},
  });
  if (res.code === 200) {
    equipTypeList.value = res.data;
    equipTypeList.value?.map((item) => {
      item.label = `${item.equipTypeName}`;
      item.value = `${item.id}`;
    });
  }
};

// 点击设备类型下拉框时，将选中的值赋给searchParam
const equipList: any = ref([]);
const deviceTypeChage = async (value: any) => {
  if (searchParam.value.deviceTypeCode) {
    searchParam.value.deviceCode = "";
    const res = await request({
      url: "/iotadmin/scaequipinfo/getlist",
      method: "post",
      data: { equipTypeId: searchParam.value.deviceTypeCode },
    });
    if (res.code === 200) {
      equipList.value = res.data;
      equipList.value?.map((item) => {
        item.label = `${item.equipName}`;
        item.value = `${item.equipCode}`;
      });
    }
  } else {
    equipList.value = [];
    searchParam.value.deviceCode = "";
  }
};

// 重置搜索框
const hadelReset = () => {
  searchParam.value.collectionTimeSearch = [getTimeStart(), getNowTime()];
  searchParam.value.startTime = getTimeStart();
  searchParam.value.endTime = getNowTime();
  searchParam.value.deviceTypeCode = "";
  searchParam.value.deviceCode = "";
  search();
};
</script>
